<template>
  <div class="chat-page">
    <div class="left-panel">
      <div class="header">
        <span>大模型分析</span>
      </div>
      <div class="button-container">
        <el-button
          class="oval-button"
          type="primary"
          @click="showCreateSessionDialog"
        >
          新建会话
        </el-button>
      </div>
      <div class="list-container">
        <el-scrollbar>
          <ul class="session-list">
            <li v-for="(session, index) in sortedSessions" :key="session.id">
              <div
                class="session-item"
                :class="{ 'active-session': session.id === currentSessionId }"
                @click="switchSession(session.id)"
              >
                <span class="session-description">{{
                  session.description
                }}</span>
                <el-dropdown
                  trigger="click"
                  @command="handleCommand(session.id, $event)"
                >
                  <span class="el-dropdown-link">
                    <i class="el-icon-more"></i>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="edit">修改</el-dropdown-item>
                    <el-dropdown-item command="delete">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            </li>
          </ul>
        </el-scrollbar>
      </div>
    </div>
    <div class="right-panel">
      <div class="chat-window">
        <div class="message-list" ref="messageList">
          <div
            v-for="(message, index) in messages"
            :key="index"
            :class="['message', message.type]"
          >
            <div v-if="message.type === 'bot'" class="avatar">
              <img :src="botAvatar" alt="avatar" />
            </div>

            <div class="message-content">
              <div class="text" v-html="message.content"></div>

              <div v-if="message.Mstype === 'chart'" class="message chart">
                <div class="chart-container">
                  <img
                    v-if="message.imageData != ''"
                    :src="'data:image/png;base64,' + message.imageData"
                    class="chart-image"
                  />
                  <a
                    v-else-if="message.chartUrl"
                    :src="message.url"
                    :href="message.chartUrl"
                    target="_blank"
                    class="chart-link"
                    >查看完整图表</a
                  >
                </div>
                <div class="chart-caption">{{ message.caption }}</div>
              </div>

              <div class="text" v-html="message.subcontent"></div>
            </div>

            <div v-if="message.type === 'user'" class="avatar">
              <img :src="userAvatar" alt="avatar" />
            </div>
          </div>
        </div>
        <div class="input-area" @keyup.enter="sendMessage">
          <el-input
            v-model="inputMessage"
            type="textarea"
            :rows="3"
            placeholder="Type your message..."
            resize="none"
          />

          <el-upload
            action="/api/ai/upload"
            :headers="uploadHeaders"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :show-file-list="false"
          >
            <el-tooltip content="上传文件">
              <el-button icon="el-icon-upload" />
            </el-tooltip>
          </el-upload>
          <!-- </el-button-group> -->

          <!-- 发送按钮 -->
          <el-button
            icon="el-icon-position"
            @click="sendMessage"
            class="send-btn"
          />
          <!-- <el-button class="send-button" type="primary" @click="sendMessage">
            <i class="el-icon-s-promotion"></i>
          </el-button> -->
        </div>
      </div>
    </div>

    <!-- 新建会话弹框 -->
    <el-dialog
      title="新建会话"
      :visible.sync="createSessionDialogVisible"
      width="30%"
      @close="resetSessionName"
    >
      <el-input v-model="sessionName" placeholder="请输入会话名称"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="createSessionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="createSession(0)">确定</el-button>
      </span>
    </el-dialog>

    <!-- 修改会话弹框 -->
    <el-dialog
      title="修改会话"
      :visible.sync="updateSessionDialogVisible"
      width="30%"
      @close="resetSessionName"
    >
      <el-input v-model="sessionName" placeholder="请输入会话名称"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="createSessionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="createSession(1)">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  createSession,
  getSessions,
  getChatList,
  delSession,
  Chat,
  updataSession,
} from "@/api/zhishiku/chat.js";
export default {
  data() {
    return {
      uploadHeaders: {
        Authorization: "Bearer " + localStorage.getItem("token"), // 根据实际情况设置
      },
      chartConfig: {
        type: "bar",
        data: {
          labels: ["Red", "Blue", "Yellow"],
          datasets: [
            {
              label: "Votes",
              data: [12, 19, 3],
            },
          ],
        },
        options: {
          scales: {
            y: {
              beginAtZero: true,
              ticks: {
                stepSize: 5,
              },
            },
          },
        },
      },

      inputMessage: "", // 用户输入的消息
      messages: [], // 聊天消息
      sessions: [
        { id: 1, description: "会话1" },
        { id: 2, description: "会话2" },
        { id: 3, description: "会话3" },
      ], // 会话列表
      currentSessionId: 1, // 当前会话ID
      userAvatar: require("@/assets/images/user.jpg"), // 用户头像
      botAvatar: require("@/assets/images/profile.jpg"), // 机器人头像
      createSessionDialogVisible: false, // 控制弹框显示
      updateSessionDialogVisible: false, // 控制弹框显示
      sessionName: "", // 会话名称
      delSe: [], //删除的session列表
      editSessioinId: "", //当前编辑的sessionId
    };
  },
  computed: {
    sortedSessions() {
      // 将当前会话项排到第一位
      return this.sessions.slice().sort((a, b) => {
        if (a.id === this.currentSessionId) return -1;
        if (b.id === this.currentSessionId) return 1;
        return 0;
      });
    },
  },
  methods: {
    handleUploadSuccess() {
      console.log("上传文件");
    },

    handleUploadError(error) {
      console.error("Upload error:", error);
    },

    //获取聊天列表
    getCharList() {
      try {
        let formData = new FormData();
        // formData.append("question",this.inputMessage);
        // formData.append("stream",false);
        formData.append("sessionId", this.currentSessionId);
        // 调用后端接口获取聊天列表
        getChatList(formData).then((response) => {
          console.log(response);
          this.messages.push({
            type: "chart",
            imageData: response.data.imageData, // 直接使用imageData字段
            title: "销售数据图表",
            caption: "根据您的要求生成的月度销售趋势",
          });
          if (response.code === 200) {
            this.messages = response.data.data[0].messages.map((msg) => ({
              type: msg.role === "assistant" ? "bot" : "user",
              content:
                msg.content?.replace(/\n/g, "<br>").replace(/##\d+\$\$/g, "") ||
                "",
              imageData: msg.image,
              Mstype: msg.Mstype,
              subcontent:
                msg.subcontent
                  ?.replace(/\n/g, "<br>")
                  .replace(/##\d+\$\$/g, "") || "",
            }));
          } else {
            this.$message.error("消息列表获取失败");
          }
        });
      } catch (error) {
        this.$message.error("请求失败，请稍后重试");
      }
    },
    //删除session会话
    deleteSession(sessionId) {
      try {
        let formData = new FormData();
        this.delSe.push(sessionId);
        formData.append("ids", this.delSe);

        // 调用后端接口获取会话列表
        delSession(formData).then((response) => {
          console.log(response);
          if (response.code === 200) {
            this.getSessionList();
            this.delSe = []; //重置
          } else {
            this.$message.error("删除失败");
          }
        });
      } catch (error) {
        this.$message.error("请求失败，请稍后重试");
      }
    },
    //获取session列表
    getSessionList() {
      try {
        let formData = new FormData();

        formData.append("require", "list");

        // 调用后端接口获取会话列表
        getSessions(formData).then((response) => {
          console.log(response);
          if (response.code === 200) {
            //更新会话列表
            this.sessions = response.data.data.map((res) => ({
              id: res.id,
              description: res.name,
            }));
          } else {
            this.$message.error("会话列表查询失败");
          }
        });
      } catch (error) {
        this.$message.error("请求失败，请稍后重试");
      }
    },
    async generateChart(prompt) {
      try {
        const response = await this.$axios.post(
          "/zhishiku/chat/generateChart",
          {
            type: "bar",
            data: {
              labels: ["Q1", "Q2", "Q3", "Q4"],
              datasets: [
                {
                  label: "销售额",
                  data: [65, 59, 80, 81],
                },
              ],
            },
          }
        );

        if (response.data.code === 200) {
          this.messages.push({
            Mstype: "chart",
            imageData: response.data.data.imageData, // 直接使用imageData字段
            title: "销售数据图表",
            caption: "根据您的要求生成的月度销售趋势",
          });
        }
      } catch (error) {
        console.error("图表生成失败:", error);
      }
    },
    sendMessage() {
      if (this.inputMessage.trim()) {
        try {
          let formData = new FormData();
          formData.append("question", this.inputMessage);
          formData.append("stream", "false");
          formData.append("session_id", this.currentSessionId);

          // 添加用户消息
          this.messages.push({ type: "user", content: this.inputMessage });
          this.inputMessage = ""; // 清空输入框
          // 调用后端接口获取聊天列表
          Chat(formData).then((response) => {
            console.log(response);
            if (response.code === 200) {
              if (response.data?.imageData) {
                this.messages.push({
                  type: "bot",
                  imageData: response.data.imageData, // 直接使用imageData字段
                  Mstype: response.data.Mstype,
                  title: "销售数据图表",
                  caption: "根据您的要求生成的月度销售趋势",
                });
              } else {
                this.messages.push({
                  type: "bot",
                  content: response.data.data.answer,
                });
              }
            } else {
              this.$message.error("消息列表获取失败");
            }
          });
        } catch (error) {
          this.$message.error("请求失败，请稍后重试");
        }

        // // 模拟 AI 回复
        // setTimeout(() => {
        //   this.messages.push({ type: 'bot', content: 'This is a response from AI.' });
        // }, 500);
      } else {
        this.$message.error("请求消息不能为空");
      }
    },
    handleCommand(sessionId, command) {
      if (command === "edit") {
        this.editSessioinId = sessionId;
        this.updateSessionDialogVisible = true;
        // this.$message(`修改会话 ${sessionId}`);
      } else if (command === "delete") {
        this.deleteSession(sessionId);
        //this.$message(`删除会话 ${sessionId}`);
      }
    },
    //切换会话
    switchSession(sessionId) {
      this.currentSessionId = sessionId;
      // 这里可以加载对应会话的消息
      this.messages = []; // 清空消息列表
      this.$message(`切换到会话 ${sessionId}`);
      this.getCharList();
    },
    showCreateSessionDialog() {
      this.createSessionDialogVisible = true;
    },
    resetSessionName() {
      this.sessionName = "";
    },
    async createSession(index) {
      //创建为 0 更新为1
      if (!this.sessionName.trim()) {
        this.$message.warning("会话名称不能为空");
        return;
      }

      try {
        let formData = new FormData();
        formData.append("name", this.sessionName);
        //创建为 0 更新为1
        if (index === 0) {
          // 调用后端接口创建会话
          createSession(formData).then((response) => {
            console.log(response);
            if (response.code === 200) {
              const newSession = {
                id: response.data.data.id,
                description: response.data.data.name,
              };
              this.sessions.push(newSession);
              this.currentSessionId = newSession.id;
              this.messages = response.data.data.messages.map((msg) => ({
                type: msg.role === "assistant" ? "bot" : "user",
                content: msg.content,
              }));
              this.createSessionDialogVisible = false;
              this.$message.success("会话创建成功");
            } else {
              this.$message.error("会话创建失败");
            }
          });
        } else {
          // 调用后端接口更新会话
          updataSession(formData, this.editSessioinId).then((response) => {
            console.log(response);
            if (response.code === 200) {
              this.getSessionList();
              this.editSessioinId = "";
              this.updateSessionDialogVisible = false;
              this.$message.success("会话更新成功");
            } else {
              this.$message.error("会话更新失败");
            }
          });
        }
        this.sessionName = "";
      } catch (error) {
        this.$message.error("请求失败，请稍后重试");
      }
    },
  },
  watch: {
    messages() {
      // 消息更新时，滚动到底部
      this.$nextTick(() => {
        const messageList = this.$refs.messageList;
        messageList.scrollTop = messageList.scrollHeight;
      });
    },
  },
  created() {
    this.getSessionList();
  },
};
</script>

<style scoped>
.chat-page {
  display: flex;
  height: 88vh;
  padding: 10px;
  background-color: #f5f5f5;
}

.left-panel {
  width: 20%;
  background-color: #e6f7ff; /* 浅蓝色背景 */
  padding: 10px;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
}

.header {
  font-size: 18px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 20px;
}

.button-container {
  text-align: center;
  margin-bottom: 20px;
}

.oval-button {
  border-radius: 20px;
  width: 80%;
}

.list-container {
  flex: 1;
  overflow: hidden;
}

.session-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.session-list li {
  margin-bottom: 10px;
}

.session-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background-color: #e6f7ff; /* 与左边列背景颜色一致 */
  border-radius: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  cursor: pointer;
}

.session-item.active-session {
  background-color: #b3e5fc; /* 当前会话项背景颜色变深 */
}

.session-description {
  flex: 1;
  margin-right: 10px;
}

.el-dropdown-link {
  cursor: pointer;
  padding: 5px;
}

.right-panel {
  width: 80%;
  padding: 10px;
  display: flex;
  flex-direction: column;
}

.chat-window {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
}

.message-list {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: #fafafa;
}

.message {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20px;
}

.message.bot {
  justify-content: flex-start;
}

.message.user {
  justify-content: flex-end;
}

.avatar {
  width: 40px;
  height: 40px;
  margin: 0 10px;
}

.avatar img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}

.message-content {
  max-width: 60%;
  padding: 10px;
  border-radius: 10px;
  background-color: #e6f7ff; /* 浅蓝色背景 */
}

.message.user .message-content {
  background-color: #409eff; /* 用户消息背景色 */
  color: white;
}

.input-area {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #fff;
  border-top: 1px solid #ddd;
}

.el-textarea {
  flex: 1;
  margin-right: 10px;
}

.send-button {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 29px;
}

.chart {
  margin: 20px auto;
  max-width: 800px;
}

.chart-image {
  width: 100%;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.chart-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
}

.chart-caption {
  color: #666;
  font-size: 12px;
  margin-top: 8px;
}
</style>
